package com.concurrent.concurrentdemo.lock;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {

    private static int num = 0;

    ReentrantLock fairLock = new ReentrantLock(true);
    ReentrantLock unFairLock = new ReentrantLock();

    public void plus() {
        try {
            unFairLock.lock();
            num++;
        } finally {
            unFairLock.unlock();
        }
    }

    @Test
    public void testPlus(){
        ExecutorService pool = Executors.newFixedThreadPool(10);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(11);
        LockDemo lockDemo = new LockDemo();
        for (int i = 0; i < 10; i++) {
            pool.execute(() -> {
                for (int j = 0; j < 10000; j++) {
                    lockDemo.plus();
                }
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        try {
            cyclicBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(num);
        pool.shutdown();
    }
}
